<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.04.20
 */

namespace App\Library\HttpResponse;

use App\Constants\Constants;
use Hyperf\HttpMessage\Cookie\Cookie;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;

class Response
{
    /**
     * @var ResponseInterface
     */
    protected $response;

    public function __construct()
    {
        $this->response = app(ResponseInterface::class);
    }

    /**
     * 统一输出
     *
     * @param int $code
     * @param string $message
     * @param array $data
     * @return PsrResponseInterface
     */
    public function showResults($code = Constants::RETURN_SUCCESS, $message = '操作成功', $data = [])
    {
        $returnData = [
            'status'  => $code == Constants::RETURN_SUCCESS,
            'code'    => $code,
            'message' => $this->_hasSql($message) ? '系统繁忙，请稍后再试！' : $message,
            'data'    => $data,
        ];

        return $this->response->json($returnData);
    }

    /**
     * @param $url
     * @param int $status
     * @return \Hyperf\HttpMessage\Server\Response
     */
    public function redirect($url, $status = 302)
    {
        return $this->_response()
            ->withAddedHeader('Location', (string)$url)
            ->withStatus($status);
    }

    /**
     * @param Cookie $cookie
     * @return Response
     */
    public function cookie(Cookie $cookie)
    {
        $response = $this->_response()->withCookie($cookie);
        Context::set(PsrResponseInterface::class, $response);
        return $this;
    }

    /**
     * @return \Hyperf\HttpMessage\Server\Response
     */
    private function _response()
    {
        return Context::get(PsrResponseInterface::class);
    }


    /**
     * 消息中是否有SQL
     *
     * @param string $message 提示信息
     * @return bool
     */
    private function _hasSql($message)
    {
        if (env('APP_ENV', 'prod') == 'dev') {
            return false;
        }

        if (stripos($message, 'SQL:') !== false || stripos($message, 'SQLSTATE') !== false) {
            return true;
        }

        return false;
    }

}
